<?php

namespace App\Http\Services;

use App\Http\Model\ActivityMall;
use App\Http\Model\ActivityPearl;
use App\Http\Model\AudioApi;
use App\Http\Model\Config;
use App\Http\Model\LoverConsumerDiamond;
use App\Http\Model\LoverCpFowlNum;
use App\Http\Model\LoverInviteUser;
use App\Http\Model\LoverRecharge;
use App\Http\Model\User;
use Illuminate\Support\Facades\Redis;

class LoverRechargeServices extends CommonServices
{
    public function __construct()
    {
        $this->loverRecharge = new LoverRecharge();
        $this->configModel = new Config();
        $this->audioApi = new AudioApi();
        $this->loverConsumerDiamond = new LoverConsumerDiamond();
        $this->loverInviteUser = new LoverInviteUser();
        $this->loverCpFowlNum = new LoverCpFowlNum();
        $this->kkaudioUser = new User();
        $this->activityPearl = new ActivityPearl();
        $this->activityMall = new ActivityMall();
    }


    public function getUserLog($user_id, $now_date, $body = [])
    {
        $log = $this->loverRecharge->getLog($user_id, $now_date);
        if (!$log) {
            //获取用户充值记录
            $allLog = $this->loverRecharge->getAllLog($user_id);
            $rank = !$allLog ? 1 : count($allLog) + 1;
            return $this->loverRecharge->create($body, $rank, $now_date);
        }
        return true;
    }

    //获取用户礼包
    public function getUserGift($user_id)
    {
        $res = $this->loverRecharge->getAllLog($user_id, ['user_id', 'rank', 'gift_log', 'status', 'created_date']);
        $count = count($res);
        foreach ($res as $k => &$v) {
            $v->is_now = 0;
            if ($k == $count - 1) {
                $log_date = $v->created_date;
                if ($log_date == date('Y-m-d', time())) {
                    $v->is_now = 1;
                }
            }
            if (!empty($v->gift_log)) {
                $log = json_decode($v->gift_log, true);
                $gift_log['pearl_num'] = $log['pearl_num'];
                if (empty($log['goods_id'])) {
                    $gift_log['status'] = 0;
                } else {
                    $gift_log['status'] = 1;
                }
                $v->gift_log = $gift_log;
            } else {
                $v->gift_log = [];
            }
        }
        if ($count < 7) {
            $nullArr = [];
            for ($i = $count + 1; $i <= 7; $i++) {
                $nullArr[$i]['user_id'] = $user_id;
                $nullArr[$i]['rank'] = $i;
                $nullArr[$i]['gift_log'] = [];
                $nullArr[$i]['status'] = -1;
                $nullArr[$i]['created_date'] = '';
                $nullArr[$i]['is_now'] = 0;
            }
            if($res){
                if ($res[$count - 1]->is_now == 0) {
                    $nullArr[$count + 1]['is_now'] = 1;
                }
            }else{
                $nullArr[$count + 1]['is_now'] = 1;
            }
            $res = array_merge($res, $nullArr);
        }
        return $res;
    }

    //用户点击礼包
    public function clickGift($user_id, $rank)
    {
        $config = $this->configModel->getShareGoodsConfig(4);
        $activity_date = explode(' - ', $config['lover_date']['value']);
        if (date('Y-m-d H:i:s', time()) > $activity_date[1]) {
            return ['code' => 406, 'msg' => '活动过期'];
        }
        $res = $this->loverRecharge->checkUserBag($user_id, $rank);
        $config = $this->configModel->getShareGoodsConfig(4);
        $pearl_num = rand(180, 600);
        $gift['user_id'] = $user_id;
        $gift['goods_id'] = '';
        $gift['goods_type'] = '';
        $gift['time_limit'] = '';
        switch ($rank) {
            case 1:
                $gift['goods_id'] = $config['lover_bubble_id']['value'];
                $gift['goods_type'] = 1;
                $gift['time_limit'] = 7;
                break;
            case 2:
                $pro2 = rand(0, 99);
                if ($pro2 < 3) {
                    $gift['goods_id'] = 36;
                    $gift['goods_type'] = 2;
                    $gift['time_limit'] = 7;
                }
                break;
            case 3:
                $gift['goods_id'] = $config['lover_headwear_id']['value'];
                $gift['goods_type'] = 1;
                $gift['time_limit'] = 7;
                break;
            case 4:
                $pro4 = rand(0, 999);
                if ($pro4 < 2) {
                    $gift['goods_id'] = 35;
                    $gift['goods_type'] = 2;
                    $gift['time_limit'] = 7;
                }
                break;
            case 5:
                $pearl_num = rand(240, 720);
                $gift['goods_id'] = 58;
                $gift['goods_type'] = 2;
                $gift['time_limit'] = 7;
                break;
            case 6:
                $pearl_num = rand(300, 780);
                $pro6 = rand(0, 999);
                if ($pro6 == 0) {
                    $gift['goods_id'] = 35;
                    $gift['goods_type'] = 2;
                    $gift['time_limit'] = 7;
                }
                break;
            case 7:
                $pearl_num = rand(420, 900);
                $gift['goods_id'] = $config['lover_ring_id']['value'];
                $gift['goods_type'] = 4;
                $gift['time_limit'] = 0;
                break;
            default:
        }

        $code = 200;
        $msg = '成功';
        $gift_log = '';
        do {
            if (!$res) {
                $code = 401;
                $msg = '不可领取';
                break;
            }
            if ($res->status == 1) {
                $code = 202;
                $msg = '已经领取';
                $gift_log = json_decode($res->gift_log, true);
                break;
            }
            if ($res->status == 0) {
                //领取礼包 发送
                if (!empty($gift['goods_id'])) { //赠送商品
                    if ($rank == 7) {//赠送钻戒
                        $api = $this->audioApi->sendRing($user_id, $gift['goods_id'], 0);
                        $this->activityMall->create($user_id, $gift['goods_id'], 5, 0, 1, 1);
                    } else {
                        $api = $this->audioApi->sendUsedMall($gift);
                        $this->activityMall->create($user_id, $gift['goods_id'], $gift['goods_type'], $gift['time_limit'], 1, 1);
                    }
                    if (!$api) {
                        write_log('loverConsumer', 'sendMallApiError', $gift);//奖励金豆api添加失败
                        $code = 402;
                        $msg = '商品赠送失败';
                        break;
                    }
                }
                $pearl_api = $this->audioApi->pearl_recharge($user_id, $pearl_num, '七夕活动领取金豆');
                if (!$pearl_api) {
                    write_log('loverConsumer', 'rechargePearlApiError', [$user_id, $pearl_num, $msg]);//奖励金豆api添加失败
                    $code = 402;
                    $msg = '金豆赠送失败';
                    break;
                }
                $this->activityPearl->create($user_id, $pearl_num, 1, 1);
                $data['status'] = 1;
                $data['gift_log'] = json_encode(array_merge($gift, ['pearl_num' => $pearl_num]));
                $res = $this->loverRecharge->updateLog($user_id, $rank, $data);
                if (!$res) {
                    $code = 402;
                    $msg = '领取失败';
                    break;
                }
                //发送消息通知
                $this->audioApi->sendMsgApi($user_id, '七夕礼包奖励已到账');
                break;
            }
        } while (false);
        return ['code' => $code, 'msg' => $msg, 'gift_log' => $gift_log];
    }

    //用户消费累计
    public function consumerLog($user_id, $diamond)
    {
        $diamond = abs($diamond);
        $log = $this->loverConsumerDiamond->getLog($user_id);
        if (!$log) {
            return $this->loverConsumerDiamond->create($user_id, $diamond);
        }
        return $this->loverConsumerDiamond->updateValue($user_id, $diamond);

    }

    public function clickDiamondGift($user_id, $rank)
    {
        $log = $this->loverConsumerDiamond->getLog($user_id);
        $config = $this->configModel->getShareGoodsConfig(4);

        $return['code'] = 200;
        $return['msg'] = '成功';
        $return['log'] = [];
        $status = 0;
        $diamond_value = 100000;
        $updateData = [];
        $gift_goods['user_id'] = $user_id;
        if (!$log) {
            $return['code'] = '401';
            $return['msg'] = '您未达标';
            return $return;
        }
        switch ($rank) {
            case 1:
                $diamond_value = 10000;
                if ($log->rank_one == 1) {
                    $status = 1;//已经领取
                    break;
                }
                $gift_goods['goods_id'] = $config['lover_one_headwear_id']['value'];
                $gift_goods['goods_type'] = 1;
                $gift_goods['time_limit'] = 7;
                $updateData['rank_one'] = 1;
                break;
            case 2:
                $diamond_value = 50000;
                if ($log->rank_two == 1) {
                    $status = 1;
                    break;
                }
                $gift_goods['goods_id'] = $config['lover_two_mount_id']['value'];
                $gift_goods['goods_type'] = 1;
                $gift_goods['time_limit'] = 7;
                $updateData['rank_two'] = 1;
                break;
            case 3:
                $diamond_value = 100000;
                if ($log->rank_three == 1) {
                    $status = 1;
                    break;
                }
                $updateData['rank_three'] = 1;
                break;
        }
        if ($status == 1) {
            $return['code'] = '201';
            $return['msg'] = '您已领取';
            return $return;
        }
        if ($diamond_value > $log->diamond_value) {
            $return['code'] = '402';
            $return['msg'] = '消费钻石数量不符合领取标准';
            return $return;
        }
        //领取
        if ($rank < 3) {
            $api_log = $this->audioApi->sendUsedMall($gift_goods);
            $this->activityMall->create($user_id, $gift_goods['goods_id'], $gift_goods['goods_type'], $gift_goods['time_limit'], 1, 2);
        } else {
            $pearl_arr = [7, 77, 520, 777];
            $pearl_key = rand(0, 3);//随机获取  0-3 金豆
            $mall_key = rand(0, 1);//随机获取商品mall
            //翻牌
            $config_date = explode(' - ', $config['lover_date']['value']);
            $activity_date = $config_date[1];
            if (date('Y-m-d H:i:s', time()) < $activity_date) {
                return ['code' => 410, 'msg' => '请在8月13日，12:00-24:00开始翻牌'];
            }
            $activity_end_date = date('Y-m-d H:i:s', strtotime($activity_date) + 43200);
            if (date('Y-m-d H:i:s', time()) > $activity_end_date) {
                return ['code' => 410, 'msg' => '请在8月13日，12:00-24:00内翻牌'];
            }
            //查看满足用户人数
            $diamond_count = $this->loverConsumerDiamond->getAllNum($activity_date);
            $award_count = $all_user = 0;
            if (count($diamond_count) == 1) {
                $all_user = $diamond_count[0]->count_user;//达标用户总数量
            } else {
                $award_count = $diamond_count[1]->count_user;//领取用户数
                $all_user = $diamond_count[1]->count_user + $diamond_count[0]->count_user;
            }
            $odds = round($award_count / $all_user, 2);
            $liang_cache = Redis::lrange('lover_liang', 0, -1);
            $rand_max = $all_user;
            $count_cache = count($liang_cache);
            if ($odds <= 0.5 && $count_cache > 4) {
                $rand_max = $all_user - $award_count;
            }
            $gift_goods['time_limit'] = 7;
            $mall_type = 1;
            switch ($mall_key) {
                case 0:
                    $gift_goods['goods_id'] = $config['lover_bubble_id']['value'];
                    $gift_goods['goods_type'] = 3;
                    $mall_type = 1;
                    break;
                case 1:
                    $gift_goods['goods_id'] = $config['lover_headwear_id']['value'];
                    $gift_goods['goods_type'] = 1;
                    $mall_type = 2;
                    break;
            }
            $type_arr[] = ['type' => 0, 'value' => '七夕快乐']; //0
            $type_arr[] = ['type' => $mall_type, 'value' => 7]; //1 商品
            $type_arr[] = ['type' => 3, 'value' => $pearl_arr[$pearl_key]]; //2金豆
            $type_key = rand(1, 2);
            $rand_num = rand(0, $rand_max);
            $is_liang = false;
            if ($rand_num < 6 && $count_cache > 0) {
                //赠送靓号
                $liang_num = Redis::lindex('lover_liang', 0);
                $type_arr[$type_key] = ['type' => 4, 'value' => $liang_num];
                $updateData['liang_num'] = $liang_num;
                Redis::lpop('lover_liang');
                //发送消息
                $this->audioApi->sendAllAppApi($user_id);
                //发送消息
                $this->audioApi->sendMsgApi($user_id, '恭喜您在七夕翻牌活动中获得靓号:' . $liang_num . '，手气爆翻天啦！');
                $is_liang = true;
            }

            shuffle($type_arr);
            $updateData['gift_log'] = json_encode($type_arr);
            if ($is_liang == true && $type_key == 1) {
                $api_log = $this->audioApi->pearl_recharge($user_id, $pearl_arr[$pearl_key], '翻牌获取金豆');
                $this->activityPearl->create($user_id, $pearl_arr[$pearl_key], 1, 2);
            } else if ($is_liang == true && $type_key == 2) {
                $api_log = $this->audioApi->sendUsedMall($gift_goods);
                $this->activityMall->create($user_id, $gift_goods['goods_id'], $gift_goods['goods_type'], $gift_goods['time_limit'], 1, 2);
            } else {
                $this->audioApi->pearl_recharge($user_id, $pearl_arr[$pearl_key], '翻牌获取金豆');
                $api_log = $this->audioApi->sendUsedMall($gift_goods);
                $this->activityPearl->create($user_id, $pearl_arr[$pearl_key], 1, 2);
                $this->activityMall->create($user_id, $gift_goods['goods_id'], $gift_goods['goods_type'], $gift_goods['time_limit'], 1, 2);
            }
        }
        if (!$api_log) {
            write_log('loverConsumer', 'sendMallApiError', $gift_goods);//奖励金豆api添加失败
            $return['code'] = '404';
            $return['msg'] = '奖励金豆失败';
            return $return;
        }
        $res = $this->loverConsumerDiamond->updateLog($user_id, $updateData);
        if (!$res) {
            write_log('loverConsumer', 'updateUserRankError', $gift_goods);
            $return['code'] = '403';
            $return['msg'] = '领取失败';
            return $return;
        }
        return $return;
    }

    public function getDiamondList($user_id)
    {
        $log = $this->loverConsumerDiamond->getLog($user_id);
        if (!$log) {
            $ret['code'] = 401;
            $ret['msg'] = '暂无记录';
            $ret['data'] = [];
            return $ret;
        }
        $log->gift_log = json_decode($log->gift_log, true);
        $ret['code'] = 200;
        $ret['msg'] = '成功';
        $ret['data'] = $log;
        return $ret;
    }

    public function send_register($phone, $sms_code, $password, $invite_uid)
    {
        $data['phone'] = $phone;
        $data['sms_code'] = $sms_code;
        $data['password'] = $password;
        $data['invite_uid'] = $invite_uid;
        $res = $this->audioApi->registerApi($data);
        $ret['code'] = 200;
        $ret['msg'] = '成功';
        $ret['data'] = [];
        do {
            if ($res['code'] != 0) {
                $ret['code'] = $res['code'];
                $ret['msg'] = $res['msg'];
                break;
            }
            $ret['data'] = $res['data'];
            break;
        } while (false);
        return $ret;
    }

    public function createInviteUser($new_user, $user_id)
    {
        $cp_log = $this->loverCpFowlNum->getFowl($user_id);
        if (!$cp_log) {
            $this->loverCpFowlNum->create($user_id);
        }
        $this->loverCpFowlNum->updateInviteNum($user_id);
        return $this->loverInviteUser->create($new_user, $user_id);
    }

    public function checkUser($user_id, $invite_uid)
    {
        $res = $this->loverInviteUser->getUser($user_id, $invite_uid);
        if (!$res) {
            write_log('loverConsumer', 'notInviteError', [$user_id, $invite_uid]);//邀请用户
            return false;
        }
        //添加邀请喜鹊数量
        $cp_fowl = $this->loverCpFowlNum->getFowl($invite_uid);
        if (!$cp_fowl) {
            return false;
        }
        if ($res->status == 0) {
            $editStatus = $this->loverInviteUser->updateStatus($user_id, $invite_uid);
            if (!$editStatus) {
                write_log('loverConsumer', 'checkInviteUserLoginError', [$user_id, $invite_uid]);//邀请用户
                return false;
            }
            $this->loverCpFowlNum->updateFowl($invite_uid);
        }
        write_log('loverConsumer', 'checkInviteUserLoginSuccess', [$user_id, $invite_uid]);//邀请用户
        return true;
    }

    public function getUserFowlNum($user_id)
    {
        $config = $this->configModel->getShareGoodsConfig(4);
        $activity_date = explode(' - ', $config['lover_date']['value']);

        //查看用户cp
        $user_cp = $this->loverCpFowlNum->getUserCp($user_id);
        $w_arr[] = intval($user_id);
        if ($user_cp) {
            $w_arr[] = $user_cp['cp_user_id'];
        }
        $fowl_num = $this->loverCpFowlNum->getFowlNum($w_arr);
        $user_fowl = $this->loverCpFowlNum->getFowl($user_id);
        $user_info = $this->kkaudioUser->getUserInfoByKkaudio($user_id);
        $img = json_decode($user_info['portrait'], true);
        $portrait = $img[0] ?? '';
        if (strpos($portrait, 'http:') === false) {
            $portrait = env('APP_PIC_DOMAIN') . $portrait;
        }
        $data['user_id'] = $user_id;
        $data['portrait'] = $portrait;
        $data['all_num'] = 0;
        $data['user_num'] = 0;
        $data['real_num'] = 0;
        $data['convert_intimacy'] = 100;

        foreach ($fowl_num as $v) {
            if ($user_id == $v->user_id) {
                $data['user_num'] = $v->fowl_num;
                $data['convert_intimacy'] = 100 - $v->consumer_intimacy_num;
                $data['real_num'] = $v->real_num;
            }
            $data['all_num'] += $v->fowl_num;
        }
        $data['is_draw'] = 0;
        if ($user_fowl) {
            $data['egg_status'] = $user_fowl->status;
            $data['is_draw'] = $user_fowl->is_draw;
        }
        if (date('Y-m-d H:i:s', time()) < $activity_date[1]) {
            $data['egg_status'] = 1;
        }

        return $data;
    }

    //兑换亲密值
    public function convert($user_id, $type = 1, $num = 1)
    {
        $config = $this->configModel->getShareGoodsConfig(4);
        $activity_date = explode(' - ', $config['lover_date']['value']);
        if (date('Y-m-d H:i:s', time()) > $activity_date[1]) {
            return ['code' => 406, 'msg' => '活动过期'];
        }
        //查看用户喜鹊
        $user_fowl_num = $this->loverCpFowlNum->getFowl($user_id);
        if (!$user_fowl_num) {
            return ['code' => 404, 'msg' => '您还未邀请用户或邀请用户未登录，请重试'];
        }
        $config = $this->configModel->getShareGoodsConfig(4);
        $code = 200;
        $msg = '成功';
        if ($user_fowl_num->real_num < $num) {
            return ['code' => 401, 'msg' => '您的喜鹊数量不足，请重试'];
        }
        if ($user_fowl_num->consumer_intimacy_num + $num > 100) {
            return ['code' => 410, 'msg' => '您的兑换亲密值超过100点'];
        }
        $intimacy_vaule = 0;
        $api = false;
        switch ($type) {
            case 1:
                //验证cp关系
                $user_cp = $this->loverCpFowlNum->getUserCp($user_id);
                if (!$user_cp) {
                    $code = 203;
                    $msg = '您还没有cp，不可以兑换亲密值';
                    break;
                }
                $api = $this->audioApi->sendIntimacyValue($user_id, $user_cp['cp_user_id'], $num);
                $this->activityPearl->create($user_id, $num, 1, 3, 3);
                $intimacy_vaule = $num;
                break;
            case 2:
                $mallData['user_id'] = $user_id;
                $mallData['goods_id'] = $config['lover_two_card_id']['value'];
                $mallData['goods_type'] = 4;
                $mallData['time_limit'] = 7;
                $api = $this->audioApi->sendUsedMall($mallData);
                $intimacy_vaule = 20;
                $this->activityMall->create($user_id, $mallData['goods_id'], $mallData['goods_type'], $mallData['time_limit'], 1, 2);
                break;
        }
        if (!$api) {
            write_log('loverConsumer', 'convertMallError', [$user_id, $user_id, 'num' => $num, 'type' => $type]);
        }

        //减少用户可用喜鹊数量
        $this->loverCpFowlNum->updateFowlToConvert($user_id, $intimacy_vaule, $type);
        return ['code' => $code, 'msg' => $msg];
    }

    public function getUserEgg($user_id)
    {
        $config = $this->configModel->getShareGoodsConfig(4);
        $activity_date = explode(' - ', $config['lover_date']['value']);
        $upDay = date('Y-m-d H:i:s', strtotime("$activity_date[1]") + 43199);
        if (date('Y-m-d H:i:s', time()) > $upDay) {
            return ['code' => 405, 'msg' => '活动已过期'];
        }
        $log = $this->loverCpFowlNum->getFowl($user_id);

        if (!$log || $log->status != 1) {
            return ['code' => 402, 'msg' => '您未达标'];
        }
        if ($log->is_draw == 1) {
            return ['code' => 403, 'msg' => '您已领取'];
        }
        if (date('Y-m-d H:i:s', time()) < $activity_date[1]) {
            return ['code' => 401, 'msg' => '请在8月13日，12:00-24:00领取彩蛋'];
        }
        $edit = $this->loverCpFowlNum->updateStatus($user_id);
        if (!$edit) {
            return ['code' => 404, 'msg' => '领取失败'];
        }
        $pearl_num = 7777;
        $api = $this->audioApi->pearl_recharge($user_id, $pearl_num, '领取彩蛋赠送金豆');
        if (!$api) {
            write_log('loverConsumer', 'rechargePearlError', [$user_id, $user_id, 'num' => $pearl_num]);
            return ['code' => '404', 'msg' => '赠送金豆失败'];
        }
        $this->activityPearl->create($user_id, $pearl_num, 1, 3);
        return ['code' => '200', 'msg' => '成功'];
    }

    public function cpEgg()
    {
        return $this->loverCpFowlNum->cp_egg();
    }

    public function getUserInfo($user_id)
    {
        $user_info = $this->kkaudioUser->getUserInfoByKkaudio($user_id);
        $img = json_decode($user_info['portrait'], true);
        $portrait = $img[0] ?? '';
        if (strpos($portrait, 'http:') === false) {
            $portrait = env('APP_PIC_DOMAIN') . $portrait;
        }
        $user_info['head_image'] = $portrait;
        return $user_info;
    }

}